package com.wooshow.base.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wooshow.base.Constant;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AES {

	private static Log log = LogFactory.getLog(AES.class);

	public static String encrypt(String sSrc, String sKey) throws Exception {
		if (sKey == null) {
			log.error("sKey is empty...");
			return null;
		}
		if (sKey.length() != 16) {
			log.error("sKey length is not equal to 16...");
			return null;
		}
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec(Constant.IvParameterSpec_PLUS.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes());
		return new BASE64Encoder().encode(encrypted);
	}

	public static String decrypt(String sSrc, String sKey) throws Exception {
		if (sKey == null) {
			log.error("sKey is empty...");
			return null;
		}
		if (sKey.length() != 16) {
			log.error("sKey length is not equal to 16...");
			return null;
		}
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec(Constant.IvParameterSpec_PLUS.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
		byte[] decrypted = new BASE64Decoder().decodeBuffer(sSrc);
		return new String(cipher.doFinal(decrypted));
	}

	public static void main(String[] args) throws Exception {
		String cKey = Constant.AES_KEY;
		String cSrc = "notroot";
		System.out.println(cSrc);
		String enString = AES.encrypt(cSrc, cKey);
		System.out.println("enString: " + enString);

		String DeString = AES.decrypt(enString, cKey);
		System.out.println("DeString: " + DeString);
	}
}